﻿using Dapper;
using erpWebapiBack.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace erpWebapiBack.ApplicationDev
{
    /**
     * Sql Server 数据库请求辅助
     */

    public class MsSqlDbRepository : IDbRepository
    {
        private MsSqlDbContext dbcontext { get; set; }

        /// <summary>
        /// 事务对象
        /// </summary>
        public DbTransaction dbTransaction { get; set; }


        public MsSqlDbRepository()
        {
            dbcontext = new MsSqlDbContext(Config.GetConnValue("BusConn"));
        }

        #region 执行SQL语句
        public int ExecuteBySql(string strSql)
        {
            try
            {
                return dbcontext.Database.Connection.Execute(strSql, null, dbTransaction);
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (dbTransaction == null)
                {
                    this.Close();
                }
            }
        }

        #endregion

        #region 事务操作

        public MsSqlDbRepository BeginTrans()
        {
            if (dbcontext.Database.Connection.State == ConnectionState.Closed)
            {
                dbcontext.Database.Connection.Open();
            }
            dbTransaction = dbcontext.Database.Connection.BeginTransaction();
            dbcontext.Database.UseTransaction(dbTransaction);
            return this;
        }
        /// <summary>
        /// 提交当前操作的结果
        /// </summary>
        public int Commit()
        {
            try
            {
                int returnValue = dbcontext.SaveChanges();
                if (dbTransaction != null)
                {
                    dbTransaction.Commit();
                    this.Close();
                }
                return returnValue;
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                if (dbTransaction == null)
                {
                    this.Close();
                }
            }
        }

        /// <summary>
        /// 把当前操作回滚成未提交状态
        /// </summary>
        public void Rollback()
        {
            this.dbTransaction.Rollback();
            this.dbTransaction.Dispose();
            this.Close();
        }

        /// <summary>
        /// 关闭连接 内存回收
        /// </summary>
        public void Close()
        {
            dbcontext.Dispose();
        }
        #endregion

        #region 实体查询

        public T FindEntity<T>(object keyValue) where T : class
        {
            try
            {
                return dbcontext.Set<T>().Find(keyValue);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public T FindEntity<T>(Expression<Func<T, bool>> condition) where T : class, new()
        {

            try
            {
                return dbcontext.Set<T>().Where(condition).FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取数据列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public IEnumerable<T> FindList<T>(string strSql) where T : class
        {
            try
            {
                return dbcontext.Database.Connection.Query<T>(strSql, null, dbTransaction);
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (dbTransaction == null)
                {
                    this.Close();
                }
            }
        }


        #endregion

        #region 新增 修改 删除

        /// <summary>
        /// 插入实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Insert<T>(T entity) where T : class
        {
            dbcontext.Entry<T>(entity).State = EntityState.Added;
            return dbTransaction == null ? this.Commit() : 0;
        }

        /// <summary>
        /// 批量插入数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public int Insert<T>(IEnumerable<T> entitys) where T : class
        {

            foreach (var entity in entitys)
            {
                dbcontext.Entry<T>(entity).State = EntityState.Added;
            }

            return dbTransaction == null ? this.Commit() : 0;
        }

        /// <summary>
        /// 更新操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update<T>(T entity) where T : class
        {
            this.UpdateEntity(entity);
            return dbTransaction == null ? this.Commit() : 0;
        }

        /// <summary>
        /// 删除操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Delete<T>(T entity) where T : class
        {
            dbcontext.Set<T>().Attach(entity);
            dbcontext.Set<T>().Remove(entity);
            return dbTransaction == null ? this.Commit() : 0;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entities"></param>
        /// <returns></returns>
        public int Delete<T>(IEnumerable<T> entities) where T : class
        {
            foreach (var entity in entities)
            {
                dbcontext.Set<T>().Attach(entity);
                dbcontext.Set<T>().Remove(entity);
            }

            return dbTransaction == null ? this.Commit() : 0;
        }

        /// <summary>
        /// EF更新实体
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="entity">实体数据</param>
        public void UpdateEntity<T>(T entity) where T : class
        {
            dbcontext.Set<T>().Attach(entity);
            Hashtable props = SqlHelper.GetPropertyInfo<T>(entity);
            foreach (string item in props.Keys)
            {
                object value = dbcontext.Entry(entity).Property(item).CurrentValue;
                if (value != null)
                {
                    if (value.ToString() == "&nbsp;")
                        dbcontext.Entry(entity).Property(item).CurrentValue = null;
                    dbcontext.Entry(entity).Property(item).IsModified = true;
                }
            }
        }



        #endregion
    }
}
